#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>

#include "ht.h"

void test_createdelete() {
	ht_table* tab = ht_create();
	ht_delete(tab);
}

void test_getset() {
	ht_table* tab = ht_create();
	char *s = NULL;

	ht_set(tab, "foo", "bar");
	ht_set(tab, "foobar", "barfoo");

	s = ht_get(tab, "foo");
	assert(s != NULL);
	assert(strcmp(s, "bar") == 0);

	s = ht_get(tab, "foobar");
	assert(s != NULL);
	assert(strcmp(s, "barfoo") == 0);

	ht_delete(tab);
}

void test_buckets() {
	ht_table* tab = ht_create();
	char *s = NULL;

	ht_set(tab, "ab", "zxcv");
	ht_set(tab, "ba", "qwer");

	s = ht_get(tab, "ab");
	assert(s != NULL);
	assert(strcmp(s, "zxcv") == 0);

	s = ht_get(tab, "ba");
	assert(s != NULL);
	assert(strcmp(s, "qwer") == 0);

	ht_delete(tab);
}

void test_settwice() {
	ht_table* tab = ht_create();
	char *s;

	ht_set(tab, "key", "value1");
	ht_set(tab, "key", "value2");

	s = ht_get(tab, "key");
	assert(s != NULL);
	assert(strcmp(s, "value2") == 0);

	ht_delete(tab);
}

void test_keycopy() {
	ht_table* tab = ht_create();
	char *s = malloc(sizeof(char) * 100);
	char *s2;
	strcpy(s, "key");
	ht_set(tab, s, "value");
	strcpy(s, "key2");

	s2 = ht_get(tab, "key");
	assert(s2 != NULL);
	assert(strcmp(s2, "value") == 0);

	free(s);
	ht_delete(tab);
}

int main(int argc, char **argv) {
	test_createdelete(); printf("OK test create delete\n");
	test_getset(); printf("OK test get set\n");
	test_buckets(); printf("OK test buckets\n");
	test_keycopy(); printf("OK test key copy\n");
	test_settwice(); printf("OK test settwice\n");
}
